package com.redisdemo.controller;

import com.redisdemo.common.RedisConstant;
import com.redisdemo.domain.Score;
import com.redisdemo.utlis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
 * <h3>redisDemo</h3>
 * <p>redis有序集合的使用</p>
 *
 * @author gdw
 * @since 2024-06-26 16:03:21
 */
@RestController
@RequestMapping("/redis")
public class RedisZsetController {
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 往zset中添加数据
     * @param score
     * @return
     */
    @PostMapping("/add")
    public  Set<ZSetOperations.TypedTuple<Object>> addZset(@RequestBody Score score){
        redisUtils.zAdd(RedisConstant.REDIS_ZSET, score.getName(), score.getScore());
        Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisUtils.zReverseRangeWithScores(RedisConstant.REDIS_ZSET, 0, 10);
        return typedTuples;
    }

    /**
     * 修改权重
     * @param score
     * @return
     */
    @PostMapping("/update")
    public  Set<ZSetOperations.TypedTuple<Object>> updateZset(@RequestBody Score score){
        redisUtils.zIncrementScore(RedisConstant.REDIS_ZSET, score.getName(), score.getScore());
        Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisUtils.zReverseRangeWithScores(RedisConstant.REDIS_ZSET, 0, 10);
        return typedTuples;
    }
}
